﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Product;
using System.Text;
using System.IO;
using Base;
using SqlOperate;
using System.Data.SqlClient;

public partial class admin_IndustryType_IndustryManage : BasePage
{
    private static string FromID = "";

    protected void Page_Load(object sender, EventArgs e)
    {
        CheckRights("column", "B1");
        if (!IsPostBack)
        {
            if (Request.QueryString["FirstID"] != "" && Request.QueryString["FirstID"] != null)
                AjaxGetData(Request.QueryString["FirstID"]);
            if (Request.QueryString["SecondID"] != "" && Request.QueryString["SecondID"] != null)
                AjaxGetData(Request.QueryString["SecondID"]);
            if (Request.QueryString["ThisID"] != "" && Request.QueryString["ThisID"] != null)
                AjaxCheckData(Request.QueryString["ThisID"]);
            if (Request.QueryString["MoveToID"] != "" && Request.QueryString["MoveToID"] != null)
                AjaxMoveData(Request.QueryString["MoveToID"]);
            Bind();
            BindFirst();
        }
    }

    private void Bind()
    {
        btnDelete.Attributes.Add("onclick", "javascript:return confirm('是否已转移该分类下的数据?删除时该分类下所有的信息都将删除!')");
        string strURl = Request.RawUrl;
        strURl = strURl.Substring(0, strURl.IndexOf(".aspx")) + ".aspx";
        string strWhere = "1=1";
        PageNo1.Strurl = strURl;
        PageNo1.FldName = "Sequence";
        PageNo1.Table = "W_IndustryType";
        PageNo1.StrGetFields = "*";
        PageNo1.PageSize = 12;
        if (Request.QueryString["page"] != "" && Request.QueryString["page"] != null)
        {
            if (Session["strWhere"] != null)
                strWhere = Session["strWhere"].ToString();
            PageNo1.Where = strWhere;
            PageNo1.Pageindex = Convert.ToInt32(Request.QueryString["page"].ToString());
            DataTable dt = PageNo1.BindView();
            if (dt.Rows.Count == 0)
            {
                lblMessage.Visible = true;
                lblMessage.Text = "暂无数据信息";
            }
            else
                lblMessage.Visible = false;
            this.grdIndustryType.DataSource = dt.DefaultView;
            grdIndustryType.DataBind();
        }
        else
        {
            int ParentID = 0;
            if (Request.QueryString["ParentID"] != null && Request.QueryString["ParentID"] != "")
            {
                ParentID = int.Parse(Request.QueryString["ParentID"]);
            }
            strWhere += " and SuperiorsID=" + ParentID;
            PageNo1.Where = strWhere;
            PageNo1.Pageindex = 1;
            Session["strWhere"] = strWhere;
            DataTable dt = PageNo1.BindView();
            if (dt.Rows.Count == 0)
            {
                lblMessage.Visible = true;
                lblMessage.Text = "暂无数据信息";
            }
            else
                lblMessage.Visible = false;
            this.grdIndustryType.DataSource = dt.DefaultView;
            grdIndustryType.DataBind();
        }
    }

    /// <summary>
    /// 加载一级分类
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void BindFirst()
    {
        DataTable dt = SqlHelper.ExecuteSqlQuery("SELECT * FROM [W_IndustryType] WHERE [SuperiorsID]=0");
        ddlFirst.DataSource = dt;
        ddlFirst.DataTextField = dt.Columns["Type"].ToString();
        ddlFirst.DataValueField = dt.Columns["ID"].ToString();
        ddlFirst.DataBind();
        ddlFirst.Items.Insert(0, new ListItem("--请选择--", "-1"));
    }

    /// <summary>
    /// 异步获取数据
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    public void AjaxGetData(string ID)
    {
        string data = "";
        DataTable dt = SqlHelper.ExecuteSqlQuery("SELECT * FROM [W_IndustryType] WHERE [SuperiorsID]=" + ID);
        if (dt.Rows.Count > 0)
        {
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                if (dt.Rows[i]["ID"].ToString().Equals(FromID))
                    continue;
                data += dt.Rows[i]["Type"].ToString() + "," + dt.Rows[i]["ID"].ToString() + ",";
            }
        }
        if (data != "")
            data = data.Remove(data.Length - 1);
        Response.Write(data);
    }

    /// <summary>
    /// 异步检查该分类下是否有子分类
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    public void AjaxCheckData(string ThisID)
    {
        string data = "";
        FromID = ThisID;
        DataTable dt = SqlHelper.ExecuteSqlQuery("SELECT * FROM [W_IndustryType] WHERE [SuperiorsID]=" + ThisID);
        if (dt.Rows.Count > 0)
        {
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                data += dt.Rows[i]["Type"].ToString() + "," + dt.Rows[i]["ID"].ToString() + ",";
            }
        }
        if (data != "")
            data = data + "a";
        else
            data = GetAllName(int.Parse(ThisID)) + ",";
        Response.Write(data);
    }

    /// <summary>
    /// 异步转移数据
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    public void AjaxMoveData(string ToID)
    {
        if (FromID == "")
        {
            Response.Write("");
            return;
        }
        if (GetRequest.isNum(ToID))
        {
            try
            {
                string fid = GetAllID(int.Parse(FromID));
                string tid = GetAllID(int.Parse(ToID));
                int k = SqlHelper.ExecuteNonQuery("SP_W_IndustryType_Move", new SqlParameter[] { new SqlParameter("@FromID", fid), new SqlParameter("@ToID", tid) });
                Response.Write("a,b,c,d");
            }
            catch (Exception ex)
            {
                Response.Write("");
            }
        }
    }

    protected void lbtnUpdateToRelease_Command(object sender, CommandEventArgs e)
    {
        TIndustryType TIndustry = new TIndustryType();
        string Content = e.CommandArgument.ToString();
        int index = Content.IndexOf("|");
        if (index < -1 || index + 1 > Content.Length)
            return;
        TIndustry.ID = int.Parse(Content.Substring(0, index));
        TIndustry.ToRelease = Convert.ToBoolean(Content.Substring(index + 1));
        IIndustryType RIndustry = new RIndustryType();
        RIndustry.UpdateToRelease(TIndustry);
        Bind();
    }

    protected void btnCancel_Click(object sender, EventArgs e)
    {
        Response.Write("<script>location='javascript:history.go(-2)'</script>");
    }

    protected void btnInsert_Click(object sender, EventArgs e)
    {
        try
        {
            int parentid = 0;
            if (Request.QueryString["ParentID"] != null && Request.QueryString["ParentID"] != "")
            {
                parentid = int.Parse(Request.QueryString["ParentID"]);
            }
            TIndustryType TIndustry = new TIndustryType();
            TIndustry.Type = this.txtType.Text;
            TIndustry.ToRelease = Convert.ToBoolean(this.radlToRelease.SelectedValue);
            TIndustry.ID = parentid;
            TIndustry.Sequence = int.Parse(this.txtSequence.Text);
            IIndustryType RIndustry = new RIndustryType();
            int m = RIndustry.Insert(TIndustry);
            lblMessages.Text = "行业分类添加成功!";
            txtType.Text = "";
            pnlIndustryType.Style.Add("display", "none");
            Bind();
        }
        catch (Exception ex)
        {
            lblMessages.Text = "行业分类添加失败!";
            pnlIndustryType.Style.Add("display", "inline");
        }
    }

    /// <summary>
    /// 生成行业分类JS
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void ButJS_Click(object sender, EventArgs e)
    {
        bool b = WriteFile();
        if (b == true)
        {
            lblMessages.Text = "脚本生成成功！";
        }
        else
        {
            lblMessages.Text = "脚本生成失败！";
        }
    }

    protected void btnDelete_Click(object sender, EventArgs e)
    {
        for (int i = 0; i < grdIndustryType.Rows.Count; i++)
        {
            CheckBox cbox = (CheckBox)grdIndustryType.Rows[i].FindControl("CheckBox1");
            if (cbox.Checked == true)
            {
                int id = int.Parse(grdIndustryType.DataKeys[i].Value.ToString());
                string AllID = GetAllID(id);
                SqlHelper.ExecuteNonQuery("SP_W_IndustryType_Delete", new SqlParameter[] { new SqlParameter("@ID", id), new SqlParameter("@AllID", AllID) });
            }
        }
        Bind();
    }

    public static bool WriteFile()
    {
        string sPath = AppDomain.CurrentDomain.BaseDirectory.ToString() + "js\\industry.js";
        Encoding code = Encoding.GetEncoding("gb2312");
        // 读取模板文件 
        StreamWriter sw = null;
        // 替换内容 
        // 这时,模板文件已经读入到名称为str的变量中了 
        string str = Base.CreateJS.CreateIndustry(); //模板页中的ShowArticle 
        // 写文件 
        try
        {
            sw = new StreamWriter(sPath, false, code);
            sw.Write(str);

            sw.Flush();
        }
        catch (Exception ex)
        {
            HttpContext.Current.Response.Write(ex.Message);
            HttpContext.Current.Response.End();
        }
        finally
        {
            sw.Close();
        }
        return true;

    }

    protected void grdIndustryType_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        int id = int.Parse(grdIndustryType.DataKeys[e.RowIndex].Value.ToString());
        string AllID = GetAllID(id);
        SqlHelper.ExecuteNonQuery("SP_W_IndustryType_Delete", new SqlParameter[] { new SqlParameter("@ID", id), new SqlParameter("@AllID", AllID) });
        Bind();
    }

    /// <summary>
    /// 排序
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void LinkButton1_Click(object sender, EventArgs e)
    {
        foreach (GridViewRow rows in this.grdIndustryType.Rows)
        {
            TextBox txt = rows.FindControl("txtSequence") as TextBox;
            System.Web.UI.WebControls.Label lbid = rows.FindControl("Lb_id") as System.Web.UI.WebControls.Label;
            int txtd = 0;
            if (GetRequest.isNum(txt.Text.ToString()))
                txtd = Convert.ToInt32(txt.Text.ToString());
            int lbxid = Convert.ToInt32(lbid.Text.ToString());
            IIndustryType RIndustry = new RIndustryType();
            RIndustry.UpdateSequence(txtd, lbxid);
        }
        Bind();
    }

    protected void grdIndustryType_RowEditing(object sender, GridViewEditEventArgs e)
    {
        grdIndustryType.EditIndex = e.NewEditIndex;
        Bind();
    }

    protected void grdIndustryType_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        int id = int.Parse(grdIndustryType.DataKeys[e.RowIndex].Value.ToString());
        string name = ((TextBox)grdIndustryType.Rows[e.RowIndex].FindControl("txtName")).Text;
        int Sequence = int.Parse(((TextBox)grdIndustryType.Rows[e.RowIndex].FindControl("txtSequence")).Text);
        TIndustryType TIndustry = new TIndustryType();
        TIndustry.ID = id;
        TIndustry.Type = name;
        TIndustry.Sequence = Sequence;
        IIndustryType RIndustry = new RIndustryType();
        RIndustry.Update(TIndustry);
        grdIndustryType.EditIndex = -1;
        Bind();
    }

    protected void grdIndustryType_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        grdIndustryType.EditIndex = -1;
        Bind();
    }

    protected void grdIndustryType_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            e.Row.Attributes.Add("onMouseOver", "SetNewColor(this);");
            e.Row.Attributes.Add("onMouseOut", "SetOldColor(this)");
            //OnClientClick="return confirm('删除时该分类下所有的信息都将删除,是否继续?')"
            LinkButton lbtn = e.Row.FindControl("lbtnDelete") as LinkButton;
            if (lbtn != null)
            {
                string ID = grdIndustryType.DataKeys[e.Row.RowIndex].Value.ToString();
                if (SetDeleteButton(ID))
                    lbtn.Attributes.Add("onclick", "javascript:return confirm('是否已转移该分类下的数据?删除时该分类下所有的信息都将删除!')");
                else
                    lbtn.Attributes.Add("onclick", "javascript:alert('该分类下还有子分类,不可进行删除!');return false;");
            }
        }
    }

    /// <summary>
    /// 数据绑定时判断有无子分类
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private bool SetDeleteButton(string ThisID)
    {
        DataTable dt = SqlHelper.ExecuteSqlQuery("SELECT * FROM [W_IndustryType] WHERE [SuperiorsID]=" + ThisID);
        if (dt.Rows.Count > 0)
            return false;
        else
            return true;
    }

    /// <summary>
    /// 异步获取分类的ID串(包括父级)
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private string GetAllID(int ID)
    {
        string S = "";
        string F = "";
        string str = "";
        DataTable dt = SqlHelper.ExecuteSqlQuery("SELECT SuperiorsID FROM [W_IndustryType] WHERE ID=" + ID);
        if (dt.Rows.Count > 0)
            S = dt.Rows[0][0].ToString();
        dt = SqlHelper.ExecuteSqlQuery("SELECT SuperiorsID FROM [W_IndustryType] WHERE ID=" + S);
        if (dt.Rows.Count > 0)
            F = dt.Rows[0][0].ToString();
        if (F != "0")
        {
            str += F;
            if (S != "0")
            {
                str += "," + S;
                return str += "," + ID;
            }
        }
        else if (S != "0")
        {
            str += S;
            return str += "," + ID;
        }
        return ID.ToString();
    }

    /// <summary>
    /// 异步获取分类的名称串(包括父级)
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private string GetAllName(int ID)
    {
        DataTable dt = SqlHelper.ExecuteSqlQuery("SELECT Type FROM [W_IndustryType] WHERE ID=" + ID);
        string th = dt.Rows[0][0].ToString();
        string S = "";
        string F = "";
        string str = "";
        string temp = "";
        dt = SqlHelper.ExecuteSqlQuery("SELECT Type,ID FROM [W_IndustryType] WHERE ID=(SELECT SuperiorsID FROM [W_IndustryType] WHERE ID=" + ID+")");
        if (dt.Rows.Count > 0)
        {
            S = dt.Rows[0][0].ToString();
            temp = dt.Rows[0][1].ToString();
        }
        if (temp != "")
        {
            dt = SqlHelper.ExecuteSqlQuery("SELECT Type FROM [W_IndustryType] WHERE ID=(SELECT SuperiorsID FROM [W_IndustryType] WHERE ID=" + temp + ")");
            if (dt.Rows.Count > 0)
                F = dt.Rows[0][0].ToString();
        }
        if (F != "")
        {
            str += F;
            if (S != "")
            {
                str += " >> " + S;
                return str += " >> " + th;
            }
        }
        else if (S != "")
        {
            str += S;
            return str += " >> " + th;
        }
        return th;
    }
}
